package com.cy.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.study.entity.MediaEntity;
import com.cy.study.exception.BusinessException;
import com.cy.study.mapper.MediaMapper;
import com.cy.study.req.MediaAddReq;
import com.cy.study.req.MediaDeleteReq;
import com.cy.study.req.MediaListReq;
import com.cy.study.service.MediaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
@RequiredArgsConstructor
public class MediaServiceImpl extends ServiceImpl<MediaMapper, MediaEntity> implements MediaService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addMedia(MediaAddReq req) {
        MediaEntity media = new MediaEntity();
        media.setCourseId(req.getCourseId());
        media.setFilePath(req.getFilePath());
        this.getBaseMapper().insert(media);
        resetMediaSort(req.getCourseId());
        return media.getId();
    }

    @Override
    public void deleteMedia(MediaDeleteReq req) {
        //先找出课程
        MediaEntity media = this.getById(req.getId());
        Integer courseId = media.getCourseId();
        boolean b = this.removeById(req.getId());
        if(!b){
            throw new BusinessException("小节不存在，请确认id之后重试");
        }
        resetMediaSort(courseId);
    }

    @Override
    public Page<MediaEntity> mediaList(MediaListReq req) {
        Page page = new Page(req.getPageNum(),req.getPageSize());
        QueryWrapper<MediaEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MediaEntity::getCourseId,req.getCourseId())
                .orderByAsc(MediaEntity::getMediaNum);
        Page<MediaEntity> res = this.getBaseMapper().selectPage(page,wrapper);
        return res;
    }

    private void resetMediaSort(Integer courseId){
        AtomicReference<Integer> count = new AtomicReference<>(1);
        QueryWrapper<MediaEntity> mediaWrapper = new QueryWrapper<>();
        mediaWrapper.lambda().eq(MediaEntity::getCourseId,courseId)
                .orderByAsc(MediaEntity::getId);
        List<MediaEntity> list = this.getBaseMapper().selectList(mediaWrapper);
        list.stream().forEach(e->{
            e.setMediaNum(count.get());
            count.getAndSet(count.get() + 1);
        });
        this.saveOrUpdateBatch(list);
    }
}
